﻿#include "FileInputStream.h"
#include "lang/Exception.h"

using namespace yzrilyzr_lang;
using namespace yzrilyzr_array;
namespace yzrilyzr_io{
	FileInputStream::FileInputStream(const File & file) : FileInputStream(file.getAbsolutePath().c_str()){}
	FileInputStream::FileInputStream(const String & filePath) :FileInputStream(filePath.c_str()){}
	FileInputStream::FileInputStream(const char * filePath){
		oneByte=0;
		fp=fopen(filePath, "rb");
		if(fp == nullptr){
			throw IOException("File open failed");
		}
	}
	FileInputStream::~FileInputStream(){
		close();
	}
	int32_t FileInputStream::read(){
		fread(&oneByte, 1, 1, fp);
		if(feof(fp))return -1;
		if(ferror(fp))throw IOException();
		readCounter++;
		return (int32_t)(oneByte & 0xff);
	}
	u_index FileInputStream::read(ByteArray & buf, u_index off, u_index len){
		if(feof(fp))return -1;
		if(ferror(fp))throw IOException();
		u_index readBytes=(u_index)fread(buf._array + off, 1, len, fp);
		readCounter+=readBytes;
		return readBytes;
	}
	void FileInputStream::close(){
		fclose(fp);
	}
}